package com.example.nophase.activity.staff;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.example.nophase.R;
import com.example.nophase.adapter.StaffProjectAdapter;
import com.example.nophase.api.RequstCommonApi;
import com.example.nophase.common.BaseCallBack;
import com.example.nophase.common.BaseResp;
import com.example.nophase.common.LoginManager;
import com.example.nophase.custom.CustomAlertDialog;
import com.example.nophase.custom.CustomDialog;
import com.example.nophase.custom.InputMoneyDialog;
import com.example.nophase.custom.TextFieldDialog;
import com.example.nophase.entity.AreaListDto;
import com.example.nophase.entity.Money;
import com.example.nophase.entity.Project;
import com.example.nophase.entity.ProjectDTO;
import com.example.nophase.entity.ProjectDetailDTO;
import com.example.nophase.entity.Section;
import com.example.nophase.entity.SysUserVO;
import com.example.nophase.entity.UserDTO;
import com.example.nophase.utils.HttpUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

public class AreaProjectActivity extends AppCompatActivity {

    @BindView(R.id.applyfor_toolbar)
    Toolbar applyforToolbar;
    @BindView(R.id.project_listview)
    ListView projectListview;
    @BindView(R.id.applyfor_from_progressbar)
    ProgressBar applyforFromProgressbar;
    @BindView(R.id.toolbar_btn)
    Button toolbarBtn;
    @BindView(R.id.content_fl)
    FrameLayout contentFl;
    @BindView(R.id.iv_background)
    ImageView ivBackground;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.lookFinance_btn)
    Button lookFinanceBtn;
    @BindView(R.id.save_applyFor_btn)
    Button saveApplyForBtn;
    @BindView(R.id.limit_money)
    TextView limitMoney;
    @BindView(R.id.instructions_money)
    TextView instructionsMoney;
    @BindView(R.id.total_Money)
    TextView totalMoney;
    @BindView(R.id.alert_money)
    LinearLayout alertMoney;
    @BindView(R.id.limit_Type)
    TextView limitType;
    @BindView(R.id.lookWageGroup_btn)
    Button lookWageGroupBtn;
    private StaffProjectAdapter adapter;
    String projectName;
    double money;
    String invoice;
    String sumCause;
    int appRegionId;
    String appRegion;
    private Boolean companyDep;
    List<ProjectDetailDTO> list = new ArrayList<ProjectDetailDTO>();
    private ProjectDetailDTO item;
    private SysUserVO userVO;
    ProjectDTO dto = new ProjectDTO();
    String accounterid;
    String accountername;
    String wageGroupId;
    String wageGroupName;
    boolean isFlag = true;
    String limit_Type;
    String appStep;//申请节点
    double step_rate;//节点比例
    double moneyLimit;//阶段限额
    double realMoney;//实际产值
    double totalMoneyNum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_area_project);
        ButterKnife.bind(this);

        userVO = LoginManager.getUserInfo(this);
        initView();
        initToolbar();
        getArea();


    }

    private void initView() {
        adapter = new StaffProjectAdapter(list, this);
        projectListview.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        applyforFromProgressbar.setVisibility(View.GONE);

    }

    private void initToolbar() {

        applyforToolbar.setTitle("");
        //设置导航图标要在setSupportActionBar方法之后
        setSupportActionBar(applyforToolbar);
        applyforToolbar.setNavigationIcon(R.drawable.ic_left_black_24dp);
        getSupportActionBar().setHomeButtonEnabled(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

            case android.R.id.home:
                this.finish();
                return true;

        }
        return super.onOptionsItemSelected(item);
    }

    @OnClick({R.id.lookFinance_btn, R.id.save_applyFor_btn, R.id.toolbar_btn, R.id.lookWageGroup_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.lookFinance_btn:
                startActivity(new Intent(AreaProjectActivity.this, LookOverFinanceMsgActivity.class));
                break;
            case R.id.lookWageGroup_btn:
                startActivity(new Intent(AreaProjectActivity.this, LookOverWageGroupMsgActivity.class));
                break;
            case R.id.save_applyFor_btn:
                if (list.size() != 0) {
                    showInvoiceInputDialog();
                } else {
                    Toast.makeText(this, "请添加项目内容", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.toolbar_btn:
                if (isFlag) {
                    getArea();
                }
                item = new ProjectDetailDTO();
                getProject(appRegionId, appRegion);
                break;


        }
    }

    /**
     * 区域下拉框
     *
     * @param namelist
     * @param listDtos
     */
    private void showAreadDialog(String[] namelist, List<AreaListDto> listDtos) {
        String title = "请选择申请区域";
        String[] name = new String[1];
        name[0] = namelist[0];
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle(title)//提示框标题
                .setIcon(R.drawable.apply_for_from)
                .setSingleChoiceItems(
                        namelist, 0,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                name[0] = namelist[which];

                            }
                        }

                )
                .setPositiveButton("确定",//提示框的两个按钮
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                System.out.println("=======" + which);
                                for (int i = 0; i < listDtos.size(); i++) {
                                    String username = listDtos.get(i).getName();
                                    System.out.println(username);
                                    if (username.equals(name[0])) {
                                        Toast.makeText(AreaProjectActivity.this, listDtos.get(i).getName(), Toast.LENGTH_LONG).show();
                                        appRegionId = listDtos.get(i).getId();
                                        appRegion = listDtos.get(i).getName();
                                        getMoney(appRegionId, appRegion);
                                    }
                                }
                                isFlag = false;
                                dialog.dismiss();

                            }
                        })

                .setNegativeButton("取消", null).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    /**
     * 项目选择框
     *
     * @param names
     */
    private void showNameInputDialog(String[] names, List<Project> list) {

        String[] name = new String[1];
        name[0] = names[0];
        AlertDialog dialog = new AlertDialog.Builder(AreaProjectActivity.this)
                .setTitle("请选择项目")//提示框标题
                .setIcon(R.drawable.apply_for_from)
                .setSingleChoiceItems(
                        names, 0,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                name[0] = names[which];

                            }
                        }
                )
                .setPositiveButton("确定",//提示框的两个按钮
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {


                                String proName = name[0];
                                if (!proName.equals("")) {
                                    projectName = proName;

                                    for (Project item : list) {
                                        if (projectName.equals(item.getProName())) {
                                            if (!companyDep) {
                                                showsection(item);
                                            } else {
                                                showMoneyInputDialog();
                                            }

                                        }
                                    }
                                    dialog.dismiss();
                                } else {
                                    Toast.makeText(AreaProjectActivity.this, "请选择项目名称", Toast.LENGTH_SHORT).show();
                                }
                            }
                        })
                .setNegativeButton("取消", null).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();


    }

    /**
     * 选择节点
     */
    private void showsection(Project item) {
        List<Section> sectionList = new ArrayList<>();
        sectionList.add(new Section("开工后", 0.25));
        sectionList.add(new Section("主体封顶完", 0.45));
        sectionList.add(new Section("砌体抹灰完成", 0.65));
        sectionList.add(new Section("竣工验收完", 0.85));
        sectionList.add(new Section("初步结算定案", 1.0));
        String[] names = new String[sectionList.size()];
        for (int i = 0; i < sectionList.size(); i++) {
            names[i] = sectionList.get(i).getNode();
        }
        String[] name = new String[1];
        name[0] = names[0];
        AlertDialog dialog = new AlertDialog.Builder(AreaProjectActivity.this)
                .setTitle("请选择项目节点")//提示框标题
                .setIcon(R.drawable.apply_for_from)
                .setSingleChoiceItems(
                        names, 0,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                name[0] = names[which];
                            }
                        }
                )
                .setPositiveButton("确定",//提示框的两个按钮
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                String proName = name[0];
                                for (Section section : sectionList) {
                                    if (proName.equals(section.getNode())) {
                                        step_rate = section.getPercentage();
                                        appStep = proName;

                                        showMoneyInputDialog();
                                    }
                                }
                            }
                        })
                .setNegativeButton("取消", null).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }


    /**
     * 输入报销款
     */
    private void showMoneyInputDialog() {

        InputMoneyDialog dialog = new InputMoneyDialog(AreaProjectActivity.this, "金额", "确定", "取消");
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.setClicklistener(new InputMoneyDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                String moneystr = dialog.getMoney();
                String productionStr = dialog.getProduction();
                double applyMoney = Double.valueOf(moneystr);
                double production = Double.valueOf(productionStr);
                realMoney = production;
                money = applyMoney;

                showCauseInputDialog();
                dialog.dismiss();
            }

            @Override
            public void doCancel() {
                dialog.dismiss();
            }
        });

    }


    /**
     * 原因输入框
     */
    private void showCauseInputDialog() {
        TextFieldDialog dialog = new TextFieldDialog(AreaProjectActivity.this, "申请原因", "请输入申请原因", "确认", "取消");
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.setClicklistener(new CustomDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                String cause = dialog.getInputMsg();
                if (!cause.equals("")) {
                    item.setProName(projectName);
                    item.setAppMoney(money);
                    item.setAuditMoney(money);
                    item.setAppReason(cause);
                    item.setRealMoney(new BigDecimal(realMoney));

                    if (step_rate != 0.0) {
                        item.setStep_rate(step_rate);
                    }

                    if (appStep != null) {
                        item.setAppStep(appStep);
                    }

                    item.setStepLimitMoney(moneyLimit);
                    item.setAppUserName(userVO.getUsername());
                    list.add(item);
                    adapter.notifyDataSetChanged();
                    ivBackground.setVisibility(View.GONE);
                    double sumMoney = Double.valueOf(totalMoneyNum);
                    for (ProjectDetailDTO item : list) {
                        sumMoney += item.getAppMoney();
                    }
                    totalMoney.setText(getdivide(new BigDecimal(sumMoney)));
                    dialog.dismiss();
                } else {
                    Toast.makeText(AreaProjectActivity.this, "请输入申请原因", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void doCancel() {
                dialog.dismiss();
            }
        });
    }

    /**
     * 发票输入框
     */
    private void showInvoiceInputDialog() {
        CustomDialog dialog = new CustomDialog(AreaProjectActivity.this, "发票", "是否有发票", "有", "无");
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.setClicklistener(new CustomDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                invoice = "是";
                getFinanceList();
                dialog.dismiss();
            }

            @Override
            public void doCancel() {
                invoice = "否";
                getFinanceList();
                dialog.dismiss();
            }
        });
    }

    /**
     * 选择财务
     *
     * @param namelist
     * @param list
     */
    private void showCheckedDialog(String[] namelist, List<UserDTO> list) {
        String[] name = new String[1];
        name[0] = namelist[0];
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("请选择一位财务人员")//提示框标题
                .setIcon(R.drawable.apply_for_from)
                .setSingleChoiceItems(
                        namelist, 0,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                name[0] = namelist[which];
                                Toast.makeText(AreaProjectActivity.this, "选择了" + namelist[which], Toast.LENGTH_LONG).show();

                            }
                        }
                )
                .setPositiveButton("确定",//提示框的两个按钮
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                System.out.println("=======" + which);
                                for (int i = 0; i < list.size(); i++) {
                                    String username = list.get(i).getUsername();
                                    System.out.println(username);
                                    if (username.equals(name[0])) {
                                        Toast.makeText(AreaProjectActivity.this, list.get(i).getUsername(), Toast.LENGTH_LONG).show();
                                        accounterid = list.get(i).getUuid();
                                        accountername = list.get(i).getUsername();
                                    }
                                }
                                if(invoice.equals("否")){
                                    getWageGroupList();
                                }else{
                                    saveAppForDetail();
                                }


                            }
                        })
                .setNegativeButton("取消", null).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    /**
     * 工资组人员弹窗
     *
     * @param namelist
     * @param list
     */
    private void showWageGroupDialog(String[] namelist, List<UserDTO> list) {
        String[] name = new String[1];
        name[0] = namelist[0];
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("请选择一位工资组批付人员")//提示框标题
                .setIcon(R.drawable.apply_for_from)
                .setSingleChoiceItems(
                        namelist, 0,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                name[0] = namelist[which];
                                Toast.makeText(AreaProjectActivity.this, "选择了" + namelist[which], Toast.LENGTH_LONG).show();

                            }
                        }
                )
                .setPositiveButton("确定",//提示框的两个按钮
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                System.out.println("=======" + which);
                                for (int i = 0; i < list.size(); i++) {
                                    String username = list.get(i).getUsername();
                                    System.out.println(username);
                                    if (username.equals(name[0])) {
                                        Toast.makeText(AreaProjectActivity.this, list.get(i).getUsername(), Toast.LENGTH_LONG).show();
                                        wageGroupId = list.get(i).getUuid();
                                        wageGroupName = list.get(i).getUsername();
                                    }
                                }

                                saveAppForDetail();
                            }
                        })
                .setNegativeButton("取消", null).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    /**
     * 获取区域信息
     */
    private void getArea() {
        SysUserVO sysUserVO = LoginManager.getUserInfo(AreaProjectActivity.this);
        List<Integer> trees = sysUserVO.getTreeIds();
        StringBuilder sb = new StringBuilder("");

        for (int tree : trees) {
            sb.append("," + tree);
        }

        Call<BaseResp<List<AreaListDto>>> call = HttpUtils.getInstance().getApiService(RequstCommonApi.class).loadArceList("Android", sb.toString().replaceFirst(",", ""));
        call.enqueue(new BaseCallBack<BaseResp<List<AreaListDto>>>() {

            @Override
            public void onSuccess(Response<BaseResp<List<AreaListDto>>> response) throws Exception {
                System.out.println(response.body().getData().toString());
                List<AreaListDto> listDtos = response.body().getData();
                System.out.println("=======+" + listDtos.toString());
                String[] name = new String[listDtos.size()];
                boolean[] arry = new boolean[listDtos.size()];
                for (int i = 0; i < listDtos.size(); i++) {
                    name[i] = listDtos.get(i).getName();
                    arry[i] = false;
                }


                showAreadDialog(name, listDtos);
            }

            @Override
            public void onFailure(String message) {

            }
        });
    }

    /**
     * 获取区域下的项目
     *
     * @param appRegionId
     * @param appRegion
     */
    public void getProject(int appRegionId, String appRegion) {
        Call<BaseResp<List<Project>>> call = HttpUtils.getInstance().getApiService(RequstCommonApi.class).loadAreaProject("ANDROID", appRegionId, appRegion);
        call.enqueue(new BaseCallBack<BaseResp<List<Project>>>() {
            @Override
            public void onSuccess(Response<BaseResp<List<Project>>> response) throws Exception {
                if (response.body().getData().size() != 0) {
                    List<Project> list = response.body().getData();
                    String[] names = new String[list.size()];
                    for (int i = 0; i < list.size(); i++) {
                        names[i] = list.get(i).getProName();
                    }
                    showNameInputDialog(names, list);
                } else {
                    CustomAlertDialog dialog = new CustomAlertDialog(AreaProjectActivity.this, "提醒", "当前区域没有配置项目信息,\n请联系管理员");
                    dialog.show();
                    dialog.setClicklistener(new CustomAlertDialog.ClickListenerInterface() {
                        @Override
                        public void doConfirm() {
                            dialog.dismiss();
                        }
                    });
                }

            }

            @Override
            public void onFailure(String message) {

            }
        });
    }

    /**
     * 获取区域信息
     * 限额
     * 类型
     *
     * @param areaId
     * @param areaName
     */
    public void getMoney(int areaId, String areaName) {
        Call<BaseResp<Money>> call = HttpUtils.getInstance().getApiService(RequstCommonApi.class).loadMomey("ANDROID", areaId, areaName);
        call.enqueue(new BaseCallBack<BaseResp<Money>>() {
            @Override
            public void onSuccess(Response<BaseResp<Money>> response) throws Exception {
                Money money = response.body().getData();
                limitMoney.setText(getdivide(money.getLimitMoney()));
                totalMoney.setText(getdivide(money.getTotalAppMoney()));
                totalMoneyNum = money.getTotalAppMoney().doubleValue();
                instructionsMoney.setText(getdivide(money.getTotalAuditMoney()));
                if(money.getCompanyDep()!= null){
                    companyDep = money.getCompanyDep();
                }else{
                    companyDep = false;
                }

                if (money.getLimitType() != null) {
                    limitType.setText("年初限额" + "(" + money.getLimitType() + ")");
                    limit_Type = money.getLimitType();
                } else {
                    limitType.setText("年初限额");
                    limit_Type = "区域";
                }

                limit_Type = money.getLimitType();
            }

            @Override
            public void onFailure(String message) {

            }
        });
    }

    /**
     * 获取财务人员信息
     */
    private void getFinanceList() {
        HttpUtils.getInstance().setAuthToken(LoginManager.getToken(this));
        Call<BaseResp<List<UserDTO>>> call = HttpUtils.getInstance().getApiService(RequstCommonApi.class).loadfinancial("ANDROID");
        call.enqueue(new BaseCallBack<BaseResp<List<UserDTO>>>() {
            @Override
            public void onSuccess(Response<BaseResp<List<UserDTO>>> response) throws Exception {
                List<UserDTO> list = response.body().getData();
                System.out.println("=======+" + list.toString());
                String[] name = new String[list.size()];
                boolean[] arry = new boolean[list.size()];
                for (int i = 0; i < list.size(); i++) {
                    name[i] = list.get(i).getUsername();
                    arry[i] = false;
                }
                showCheckedDialog(name, list);
            }

            @Override
            public void onFailure(String message) {

            }
        });

    }

    /**
     * 获取工资组人员
     */
    private void getWageGroupList() {
        HttpUtils.getInstance().setAuthToken(LoginManager.getToken(this));
        Call<BaseResp<List<UserDTO>>> call = HttpUtils.getInstance().getApiService(RequstCommonApi.class).loadWageGroup("ANDROID");
        call.enqueue(new BaseCallBack<BaseResp<List<UserDTO>>>() {
            @Override
            public void onSuccess(Response<BaseResp<List<UserDTO>>> response) throws Exception {
                List<UserDTO> list = response.body().getData();
                System.out.println("=======+" + list.toString());
                String[] name = new String[list.size()];
                boolean[] arry = new boolean[list.size()];
                for (int i = 0; i < list.size(); i++) {
                    name[i] = list.get(i).getUsername();
                    arry[i] = false;
                }
                showWageGroupDialog(name, list);
            }

            @Override
            public void onFailure(String message) {

            }
        });

    }

    /**
     * 提交信息
     */
    public void saveAppForDetail() {

        Double money = 0.0;
        for (ProjectDetailDTO item : list) {
            money += item.getAppMoney();
        }
        dto.setAppMoney(money);
        dto.setDtos(list);
        dto.setAppUserName(userVO.getUsername());
        dto.setAppCompany(userVO.getDepartment());
        dto.setAccounterid(accounterid);
        dto.setAccounterName(accountername);
        dto.setAppUsertel(userVO.getPhone());
        dto.setInvoice(invoice);
        dto.setAppReason(sumCause);
        dto.setAuditMoney(money);
        dto.setStatus("审核中");
        dto.setAppRegionId(appRegionId);
        if(wageGroupId != null && wageGroupName != null){
            dto.setGzzUuid(wageGroupId);
            dto.setGzzUserName(wageGroupName);
        }

        dto.setAppRegion(appRegion);
        dto.setGzzStatus("未处理");
        dto.setAppUsertel(userVO.getPhone());
        dto.setLimitType(limit_Type);
        dto.setAppType("区域申请");
        HttpUtils.getInstance().setAuthToken(LoginManager.getToken(this));
        applyforFromProgressbar.setVisibility(View.VISIBLE);
        Call<BaseResp<Object>> call = HttpUtils.getInstance().getApiService(RequstCommonApi.class).saveAppForDetail("ANDROID", dto);
        call.enqueue(new BaseCallBack<BaseResp<Object>>() {
            @Override
            public void onSuccess(Response<BaseResp<Object>> response) throws Exception {
                applyforFromProgressbar.setVisibility(View.GONE);
                String code = response.body().getCode();
                boolean success = response.body().getSuccess();
                if (code.equals("200") && success) {
                    Toast.makeText(AreaProjectActivity.this, "提交成功", Toast.LENGTH_LONG).show();
                    AreaProjectActivity.this.finish();
                }
            }

            @Override
            public void onFailure(String message) {
            }
        });
    }

    private String getdivide(BigDecimal val1) {
        BigDecimal val2 = new BigDecimal(10000);
        BigDecimal decimal = val1.divide(val2);
        if (decimal.intValue() > 1) {
            //方式一
            DecimalFormat df1 = new DecimalFormat("0.00");
            String str = df1.format(decimal.doubleValue());
            return str + "万";
        } else {
            return val1 + "元";
        }
    }
}
